"use client"
import { useSearchParams, useRouter, useParams } from 'next/navigation'
import Custom from '@/components/layouts/custom'
import Back from 'public/icons/layout/back.svg'
import styles from './TagEditor.module.scss'
import { Form, Input, Button, Toast, Dialog } from 'antd-mobile'
import { useEffect } from 'react'
import EmojiSelector from '@/components/pageComponents/tagPage/EmojiSelector'
import { cFetch } from '@/lib/Http'
export default function(){
  const kind = useSearchParams().get('kind')
  const params = useParams()
  const pid = params.id
  const router = useRouter()
  
  const [form] = Form.useForm()
  const defaultValueObj={ 
    id: pid,
    name: '',
    sign: '',
    kind: kind ?? 'expenses',
   }
  useEffect(() => {
    if(pid){
      cFetch.get<Record<string,any>>(`/tag/${pid}`).then(res=>{
        form.setFieldsValue(res.resource)
      }).catch(err=>{
        console.error(err)
      })
    }else{
      form.setFieldsValue(defaultValueObj)
    }
  }, [])
  const handleSetSign = (sign: string) => {
    form.setFieldValue('sign', sign)
  }
  const handleSubmit = async (value: any) => {
    const formData ={ 
      id: pid,
      kind, 
      ...value
    }
    if(pid){
      cFetch.patch<Record<'msg', string>>('/tag', formData, { _autoLoading: true }).then(res=>{
        Toast.show({ icon: 'success', content: res.msg })
        router.back()
      }).catch(err=>{
        throw new Error(err)
      })
    }else{
      cFetch.post<Record<'msg', string>>('/tag', formData, { _autoLoading: true }).then(res=>{
        Toast.show({ icon: 'success', content: res.msg })
        setTimeout(() => {
          router.push('/home/editPage')
        }, 500)
      }).catch(err=>{
        console.error(err)
      })
    }
  }
  const handleValidateFailed = (value: any) => {
    const content = value.errorFields[0].errors[0] ?? '请完善表单'
    Toast.show({ icon: 'fail', content })
  }
  const delAllTagData = () => {
    Dialog.confirm({
      content: '请确认是否删除标签及记账？',
      onConfirm: async () => {
        const res =await cFetch.delete<Resource<Tag>>( `/tag/${pid}`,{ with_items:'true'})
        Toast.show({ icon: 'success', content: res.msg, position: 'bottom', })
        router.back()
      },
    })
  }
  return (
    <Custom header={
      <div className="operateTitle">
        <Back height={24} width={24} fill="currentColor" onClick={()=>router.back()}/>
        {pid ? <h3>编辑标签</h3> : <h3>新建标签</h3>}
      </div>
    }>
      <section className={styles.tagEditSec}>
        <Form form={form} layout='horizontal' mode="card" onFinish={handleSubmit} onFinishFailed={handleValidateFailed}
          footer={ <Button block type='submit' color='primary'> 提交 </Button> }
        >
          <Form.Item name='name' label='标签名' rules={[ { required: true, message: '请输入标签名' }]}>
            <Input placeholder='请输入标签名' maxLength={4}/>
          </Form.Item>
          <Form.Item name='sign' label='符号' rules={[ { required: true, message: '请选择符号' }]}>
            <Input placeholder='请选择下方符号' readOnly/>
          </Form.Item>
          <EmojiSelector setSign={handleSetSign}/>
          <p>记账时长按标签即可进行编辑</p>
        </Form>
        {pid && <footer> <Button block color="danger" onClick={delAllTagData}> 删除标签（对应记账也会被删除） </Button> </footer>}
      </section>
    </Custom>
  )
}